﻿using RayDen.Library.Core.Primitives;
using RayDen.RayEngine.Samplers;

namespace RayDen.RayEngine.VertexFramework
{
    public class GenericPathIntegrator : PathBuffer<GenericPathSampler>
    {

        public GenericPathIntegrator() { }

        public GenericPathIntegrator(int maxPaths, RayEngineScene scene, ImageFilmBase agg, ISampler sm, SurfaceSampler ss)
            : base(maxPaths, scene, agg, sm, ss)
        {
        }

        protected override PathSamplerBase CreatePathSampler()
        {
            return new GenericPathSampler();
        }

        internal override void AdvancePaths(RayBuffer rayBuffer)
        {
            for (int i = firstPath; i != lastPath; i = (i + 1) % paths.Count)
            {
                paths[i].Advance(rayBuffer, this.sampleBuffer, this.OnSplat);
                var path = (GenericPathSampler)paths[i];

                if (path.PathState == GenericPathSamplerState.Evaluation)
                {

                    var rad = new RgbSpectrum();

                    for (int j = 1; j < path.currentVertice; j++)
                    {
                        switch (path.vertices[j].Type)
                        {
                            case PathVertexType.Environment:
                                rad += ((EnvironmentPathElement)path.vertices[j]).Throughput;
                                break;
                            case PathVertexType.Lightsource:

                                break;
                            case PathVertexType.Geometry:

                                break;
                        }
                    }

                    sampleBuffer.SplatSample(path.Sample, rad);
                    path.InitPath(this);
                }

                if (this.sampleBuffer.IsFull())
                {
                    this.statsTotalSampleCount += this.sampleBuffer.GetSampleCount();
                    // Splat all samples on the film
                    this.film.SplatSampleBuffer(true, sampleBuffer);
                    this.sampleBuffer = this.film.GetFreeSampleBuffer();
                }
            }

            firstPath = (lastPath + 1) % paths.Count;
        }

    }
}